package com.miracle9.game.service;

import com.miracle9.game.bean.Pager;
import com.miracle9.game.bean.RoomStatus;
import com.miracle9.game.dao.*;
import com.miracle9.game.entity.*;
import com.miracle9.game.enums.GameTypeEnums;
import com.miracle9.game.server.message.StorageMethodEntity;
import com.miracle9.game.server.message.BcbmSocketHandler;
import com.miracle9.game.util.GameParameterAssist;
import com.miracle9.game.util.MyUtil;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("bcbmDeskService")
public class BcbmDeskService extends BaseService {

    private static final Logger logger = Logger.getLogger(WaterDeskService.class);
    private int gameType = GameTypeEnums.GT_52.getType();
    private String gameName = GameTypeEnums.GT_52.getName();
    private String gameNameEn = GameTypeEnums.GT_52.getEname();
    @Autowired
    private DeskService deskService;
    @Autowired
    private UserServiceDao userServiceDao;
    @Autowired
    private AdminServiceDao adminServiceDao;
    @Autowired
    private AdminLogServiceDao adminLogServiceDao;
    @Autowired
    private BcbmRoomDao roomDao;
    @Autowired
    private BcbmDeskDao deskDao;
    @Autowired
    private BcbmDeskResultServiceDao deskResultDao;
    @Autowired
    private SystemConfigServiceDao systemConfigServiceDao;

    public BcbmDesk getBcbmDesk(int id) {
        return this.deskDao.getBcbmDesk(id);
    }

    private void addAdminLog(IoSession session, BcbmDesk desk, int isExitSeat, int isAutoKick, String content, String contentEn) {
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), content, 1, admin.getType(), contentEn);
        this.adminLogServiceDao.addAdminLog(adminLog);
        for (IoSession s2 : BcbmSocketHandler.x) {
            com.miracle9.game.server.message.AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(s2, "manageService/updateDesk", new Object[]{desk.getId(), isExitSeat, isAutoKick}));
        }
    }

    private void addAdminLog(IoSession session, String content, String contentEn) {
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), content, 1, admin.getType(), contentEn);
        this.adminLogServiceDao.addAdminLog(adminLog);
    }

    private String getRoomTypeName(int roomId) {
        return roomId == 1 ? "练习" : "竞技";
    }
    private String getRoomTypeNameEn(int roomId) {
        return roomId == 1 ? "practice" : "compete";
    }

    public synchronized Map<String, Object> addBcbmDesk(BcbmDesk desk, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        int deskCount = this.deskDao.getQuantityByRoomId(desk.getRoomId());
        BcbmRoom fr = this.roomDao.getById(desk.getRoomId());
        if (deskCount >= fr.getDeskNum()) {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "deskNumOverrun"));
            return result;
        }
        int countByName = this.deskDao.q_CreateSqlInt("select count(*) from BcbmDesk where name=?", new Object[]{desk.getName()});
        if (countByName > 0) {
            result.put("success", Boolean.FALSE);
            result.put("message", MyUtil.getProperties(resultInt(session), "deskNameExist"));
            return result;
        }
        Integer maxOrderBy = (Integer) this.deskDao.q_CreateSql("select max(orderBy) from BcbmDesk where roomId = ?", new Object[]{desk.getRoomId()}).uniqueResult();
        if (maxOrderBy != null) {
            desk.setOrderBy(maxOrderBy + 1);
        } else {
            desk.setOrderBy(1);
        }
        this.deskDao.saveDesk(desk);
        String content = gameName + "：在" + getRoomTypeName(desk.getRoomId()) + "添加了新桌，ID为 " + desk.getId();
        String contentEn = gameNameEn + ": Add a new table into " + getRoomTypeNameEn(desk.getRoomId()) + " room which ID is " + desk.getId();
        addAdminLog(session, content, contentEn);
        //同步状态
        RoomStatus rs = GameParameterAssist.bD;
        if (desk.getRoomId() == 1) {
            rs.room1StartNum52 += 1;
            rs.room1RemainNum52 -= 1;
        } else {
            rs.room2StartNum52 += 1;
            rs.room2RemainNum52 -= 1;
        }
        for (Map.Entry<Integer, IoSession> entry : GameParameterAssist.be.entrySet()) {
            com.miracle9.game.server.message.AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(entry.getValue(), "syncRoomStatus", new Object[]{rs}));
        }
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        for (IoSession s : BcbmSocketHandler.x) {
            com.miracle9.game.server.message.AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(s, "manageService/addDesk", new Object[]{desk}));
        }
        SystemConfig config = this.systemConfigServiceDao.getSystemConfig();
        if (config.getOpenFishGame() == 0) {
            this.systemConfigServiceDao.ifTypeUpdate(gameType, 1);
            deskService.gameRunNotice();
        }
        return result;
    }

    public BcbmDesk[] getBcbmDeskList(IoSession session) {
        List<BcbmDesk> desks = this.deskDao.getBcbmDeskList();
        for (BcbmDesk d : desks) {
            List<User> us = GameParameterAssist.bcbmUserList.get(d.getId());
            if (us != null) {
                d.setOnlineNumber(us.size());
            } else {
                d.setOnlineNumber(0);
            }
        }
        return desks.toArray(new BcbmDesk[0]);
    }

    public Map<String, Object> updateBcbmDesk(BcbmDesk desk, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        int deskCount = this.deskDao.q_CreateSqlInt("select count(*) from BcbmDesk where name=? and id!=?", new Object[]{desk.getName(), desk.getId()});
        if (deskCount > 0) {
            result.put("success", Boolean.valueOf(false));
            result.put("message", MyUtil.getProperties(Integer.valueOf(resultInt(session)), "deskNameExist"));
            return result;
        }
        BcbmDesk old = this.deskDao.getBcbmDesk(desk.getId());
        if ((old.getExchange() != desk.getExchange()) || (old.getSiteType() != desk.getSiteType())) {
            this.deskDao.updateSumById(old.getId());
            for (IoSession s : BcbmSocketHandler.x) {
                com.miracle9.game.server.message.AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(s, "manageService/cleanDesk", new Object[]{Integer.valueOf(desk.getId())}));
            }
        }
        int isExitSeat = 0;
        int isAutoKick = 0;
        StringBuilder content = new StringBuilder();
        StringBuilder contentEn = new StringBuilder();
        String roomTypeName = getRoomTypeName(desk.getRoomId());
        String roomTypeNameEn = getRoomTypeNameEn(desk.getRoomId());
        content.append(gameName + "：修改了" + roomTypeName + "桌，ID为 " + desk.getId());
        contentEn.append(gameNameEn + ": Change the parameter of " + roomTypeNameEn + " table which ID is " + desk.getId());
        if (!old.getName().equals(desk.getName())) {
            isExitSeat = 1;
            content.append("，修改名称为“" + desk.getName() + "”");
            contentEn.append(",Its name has been changed to " + desk.getName());
        }
        if (old.getMinGold() != desk.getMinGold()) {
            isExitSeat = 1;
            content.append("，修改最少携带为“" + desk.getMinGold() + "”");
            contentEn.append(",Change the min carry of coins to " + desk.getMinGold());
        }
        if (old.getAutoKick() != desk.getAutoKick()) {
            isAutoKick = 1;
            if (desk.getAutoKick() == 0) {
                content.append("，关闭自动踢出挂机玩家");
                contentEn.append(",Turn off the function of kicking out hang up player");
            } else {
                content.append("，开启自动踢出挂机玩家");
                contentEn.append(",Turn on the function of kicking out hang up player");
            }
        }
        if (old.getSiteType() != desk.getSiteType()) {
            isExitSeat = 1;
            if (desk.getSiteType() == 0) {
                content.append("，修改场地为“10人场地”");
                contentEn.append(",Chang the site to small");
            } else if (desk.getSiteType() == 1) {
                content.append("，修改场地为“20人场地”");
                contentEn.append(",Chang the site to medium");
            } else {
                content.append("，修改场地为“100人场地”");
                contentEn.append(",Chang the site to Big");
            }
        }
        if (old.getExchange() != desk.getExchange()) {
            isExitSeat = 1;
            content.append("，修改一币分值为“" + desk.getExchange() + "”");
            contentEn.append(",Chang the coin value to " + desk.getExchange());
        }
        if (old.getOnceExchangeValue() != desk.getOnceExchangeValue()) {
            isExitSeat = 1;
            content.append("，修改单次上分设置为“" + desk.getOnceExchangeValue() + "”");
            contentEn.append(",Chang the coin conversion has to " + desk.getOnceExchangeValue());
        }
        if (old.getState() != desk.getState()) {
            if (desk.getState() == 0) {
                content.append(",修改桌状态为“锁定”");
                contentEn.append(",Change the table state to lock");
            } else {
                content.append(",修改桌状态为“开放”");
                contentEn.append(",Change the table state to open");
            }
        }
        this.deskDao.updateDeskInfo(desk);
        addAdminLog(session, desk, isExitSeat, isAutoKick, content.toString(), contentEn.toString());
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public Map<String, Object> deleteBcbmDesk(int id, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        BcbmDesk desk = this.deskDao.getBcbmDesk(id);
        this.deskDao.deleteById(id, desk.getRoomId());
        deskService.recordDeleteDesk(gameType, id, desk.getExchange());
        RoomStatus rs = GameParameterAssist.bD;
        if (desk.getRoomId() == 1) {
            rs.room1StartNum52 -= 1;
            rs.room1RemainNum52 += 1;
        } else {
            rs.room2StartNum52 -= 1;
            rs.room2RemainNum52 += 1;
        }
        for (Map.Entry<Integer, IoSession> entry : GameParameterAssist.be.entrySet()) {
            com.miracle9.game.server.message.AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(entry.getValue(), "syncRoomStatus", new Object[]{rs}));
        }
        String content = gameName + "：删除了ID为 " + id + " 的桌子";
        String contentEn = gameNameEn + "：Delete a table which ID is " + id;
        addAdminLog(session, content, contentEn);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        for (IoSession s : BcbmSocketHandler.x) {
            com.miracle9.game.server.message.AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(s, "manageService/deleteDesk", new Object[]{desk}));
        }
        GameParameterAssist.bcbmUserList.remove(desk.getId());
        return result;
    }

    public User[] getBcbmDeskUser(int deskId, IoSession session) {
        List<User> users = GameParameterAssist.bcbmUserList.get(deskId);
        if (users == null) {
            users = new ArrayList<>();
        }
        BcbmDesk desk = this.deskDao.getBcbmDesk(deskId);
        for (User u : users) {
            User user = (User) this.userServiceDao.getById(u.getId());
            u.setGameGold(user.getGameGold());
            u.setExpeGold(user.getExpeGold());
            if (desk.getRoomId() == 1) {
                u.setCurrentGameScore(user.getExpeScore());
            } else {
                u.setCurrentGameScore(user.getGameScore());
            }
            u.setPromoterId(user.getPromoterId());
            u.setPromoterName(user.getPromoterName());
            u.setNickname(user.getNickname());
        }
        return users.toArray(new User[0]);
    }

    public Map<String, Object> getBcbmDeskData(int deskId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        BcbmDesk desk = this.deskDao.getBcbmDesk(deskId);
        result.put("sumYaFen", desk.getSumYaFen());
        result.put("sumDeFen", desk.getSumDeFen());
        return result;
    }

    public Map<String, Object> cleanBcbmDeskData(int deskId, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        this.deskDao.updateSumById(deskId);
        String content = gameName + "：清零了ID为 " + deskId + " 桌子的总押分和总得分";
        String contentEn = gameNameEn + ": Clean up the total bet and total score of the table which ID is " + deskId;
        addAdminLog(session, content, contentEn);
        for (IoSession s : BcbmSocketHandler.x) {
            com.miracle9.game.server.message.AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(s, "manageService/cleanDesk", new Object[]{deskId}));
        }
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public Pager getBcbmDeskResult(int id, String startDate, String endDate, Pager pager, IoSession session) {
        if ("".equals(pager.getOrderBy())) {
            pager.setOrderBy("datetime");
            pager.setOrder("desc");
        }
        endDate = MyUtil.DateByDayCalendar(endDate, 1);
        Pager result = this.deskResultDao.q_CreateSqlsPager("from BcbmDeskResult where deskId = ? and datetime>=? and datetime<?", pager, new Object[]{id, startDate, endDate});
        Object[] os = pager.getList();
        for (Object o : os) {
            BcbmDeskResult deskResult = (BcbmDeskResult) o;
            setResultStr(deskResult);
        }
        return result;
    }

    public void setResultStr(BcbmDeskResult deskResult) {
        if(deskResult.getCarNumber()==0){
            deskResult.setResultStr("雷克萨斯");
        }
        else if(deskResult.getCarNumber()==1){
            deskResult.setResultStr("大众");
        }
        else if(deskResult.getCarNumber()==2){
            deskResult.setResultStr("奔驰");
        }
        else if(deskResult.getCarNumber()==3){
            deskResult.setResultStr("宝马");
        }
        else if(deskResult.getCarNumber()==4){
            deskResult.setResultStr("保时捷");
        }
        else if(deskResult.getCarNumber()==5){
            deskResult.setResultStr("玛莎拉蒂");
        }
        else if(deskResult.getCarNumber()==6){
            deskResult.setResultStr("兰博基尼");
        }
        else if(deskResult.getCarNumber()==7){
            deskResult.setResultStr("法拉利");
        }
    }

}